<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医生ID" prop="doctorId">
        <el-input
            v-model="queryParams.doctorId"
            placeholder="请输入医生ID"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室名称" prop="departmentName">
        <el-select
            v-model="queryParams.departmentName"
            placeholder="请输入科室名称"
            clearable
            filterable
        >
          <el-option
              v-for="item in departmentOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属院区" prop="hospitalArea">
        <el-select
            v-model="queryParams.hospitalArea"
            placeholder="请输入所属院区"
            clearable
            filterable
            @keyup.enter="handleQuery"
        >
          <el-option
              v-for="item in hospitalarea"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="科室位置" prop="location">
        <el-input
            v-model="queryParams.location"
            placeholder="请输入科室位置"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室简介" prop="introduction">
        <el-input
            v-model="queryParams.introduction"
            placeholder="请输入科室简介"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科室状态" prop="delFlag">
        <el-radio-group v-model="queryParams.delFlag" >
          <el-radio
              v-for="item in status"
              :key="item.label"
              :label="item.label"
          >{{ item.value }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['system:departments:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:departments:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:departments:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:departments:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="departmentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="科室ID" align="center" prop="id" />
      <el-table-column label="医生" align="center" prop="doctorName"/>
      <el-table-column label="科室名称" align="center" prop="departmentName" />
      <el-table-column label="所属院区" align="center" prop="hospitalArea" />
      <el-table-column label="科室位置" align="center" prop="location" />
      <el-table-column label="科室简介" align="center" prop="introduction" />
      <el-table-column label="状态：0:正常 1:删除" align="center" prop="delFlag" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:departments:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:departments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改科室信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="departmentsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生" prop="doctorsName">
          {{form.doctorsName}}
        </el-form-item>
        <el-form-item label="科室名称" prop="departmentName">
          {{form.departmentName}}
        </el-form-item>
        <el-form-item label="所属院区" prop="hospitalArea">
<!--          <el-radio-group v-model="form.hospitalArea">-->
<!--            <el-radio-->
<!--              v-for="(item, index) in hospitalarea"-->
<!--              :key="index"-->
<!--              :label="item"-->
<!--            >{{item}}</el-radio>-->
<!--          </el-radio-group>-->
          {{form.hospitalArea}}
        </el-form-item>
        <el-form-item label="科室位置" prop="location">
          {{form.location}}
        </el-form-item>
        <el-form-item label="科室简介" prop="introduction">
          <el-input v-model="form.introduction" placeholder="请输入科室简介" />
        </el-form-item>
        <el-form-item label="科室状态" prop="delFlag">
          <el-radio-group v-model="form.delFlag" >
            <el-radio
                v-for="item in status"
                :key="item.label"
                :label="item.label"
            >{{ item.value }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Departments">
import { listDepartments, getDepartments, delDepartments,
  addDepartments, updateDepartments, getDepartmentNames,getHospitalCampusName
  } from "@/api/system/departments"
import { getDoctorsNameByDepartment } from "@/api/system/doctors"
import { listCampus } from "@/api/system/hospitalCampus.js"
import {reactive} from "vue";

const departmentOptions = ref([]) // 存储科室名称选项

const { proxy } = getCurrentInstance()

const departmentsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const hospitalarea = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const status = ref([{
  "label": "0",
  "value": "正常"
}, {
  "label": "1",
  "value": "删除"
}])
const queryParams1 = reactive({
  pageNum: 1,
  pageSize: 50,
  campusName: '' // 搜索关键词（院区名称）
})
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    doctorId: null,
    departmentName: null,
    hospitalArea: null,
    location: null,
    introduction: null,
    delFlag: null
  },
  rules: {
    departmentName: [
      { required: true, message: "科室名称不能为空", trigger: "blur" }
    ],
    delFlag: [{ required: true, message: "状态不能为空", trigger: "blur"}]
  }
})

const { queryParams, form, rules } = toRefs(data)

function get() {
  listCampus(queryParams1).then(response => {
    console.log(response.data)
    for (var i = 0; i < response.data.length; i++){
      for (var j = 0; j < response.data[i].navigations.length; j++){
        for(var k = 0; k < response.data[i].navigations[j].floorIndex.split( ",").length; k++){
          let b={
            location:response.data[i].navigations[j].floor,
            departmentName:response.data[i].navigations[j].floorIndex.split( ",")[k],
            hospitalArea:response.data[i].campusName,
            delFlag:1,
            campusId:response.data[i].id
          }
          addDepartments(b)
        }
      }
    }
  })
}
//获取院区名称列表
getHospitalCampusName().then(response => {
  for(let i = 0;i < response.length; i++){
    hospitalarea.value.push(response[i].campusName)
  }
})

// 获取科室名称列表
function getDepartmentOptions() {
  getDepartmentNames().then(response => {
    departmentOptions.value = response.data
  })
}

/** 查询科室信息列表 */
async function getList() {
  loading.value = true
  //console.log(queryParams.value)
  await listDepartments(queryParams.value).then(async response => {
    departmentsList.value = response.rows
    total.value = response.total
    loading.value = false
    let a=[]
    let b=[]
    let c=[]
    for (let i = 0; i < departmentsList.value.length; i++) {
      // console.log(departmentsList.value[i].departmentName)
      // console.log((await getDoctorsNameByDepartment(departmentsList.value[i].departmentName)))
       a.push((await getDoctorsNameByDepartment(departmentsList.value[i].departmentName)))
      b.push(a[i].length)
      c.push((departmentsList.value[i].departmentName))
    }
    // console.log(a)
    // console.log(b)
    // console.log(c)
     departmentsList.value = departmentsList.value.map((item,index) => ({
      ...item,
      doctorName: a[index].toString()
    }))
    // console.log(departmentsList.value)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    doctorId: null,
    departmentName: null,
    hospitalArea: null,
    location: null,
    introduction: null,
    delFlag: null,
    doctorsName: null
  }
  proxy.resetForm("departmentsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加科室信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getDepartments(_id).then(async response => {
    // console.log(response)
     getDoctorsNameByDepartment(response.data.departmentName).then(response => {
      form.value.doctorsName = response.toString()
      // console.log(response)
    })
    form.value = response.data
    // console.log(form.value)
    open.value = true
    title.value = "修改科室信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["departmentsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        //console.log(form)
        updateDepartments(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDepartments(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除科室信息编号为"' + _ids + '"的数据项？').then(function() {
    return delDepartments(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/departments/export', {
    ...queryParams.value
  }, `departments_${new Date().getTime()}.xlsx`)
}

// // 在页面初始化时获取科室选项
// onMounted(() => {
//   getDepartmentOptions()
// })
onActivated(()=>{
  getList()
  getDepartmentOptions()
})
getList()
</script>
